package com.heima.behavior.advice;

import com.heima.behavior.dto.BehaviorDto;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

@Component
@Aspect
public class BehaviorAdvice {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Around("execution(* com.heima.behavior.service.impl.*.*(..))")
    public Object saveBehaviorToRedis(ProceedingJoinPoint pjp){
        //记录当前登录人的行为操作
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        String methodName = method.getName();
        //判断方法是否以save开头
        if(methodName.startsWith("save")){
            Object[] args = pjp.getArgs();
            BehaviorDto dto = (BehaviorDto) args[0];
              // 0  关注 点赞 不喜欢 收藏    1 取消关注 取消点赞 取消不喜欢 取消收藏
            if(dto.getOperation()==0){
                redisTemplate.boundValueOps( methodName +dto.getUserId()+"_"+dto.getEquipmentId()+"_"+dto.getAuthorId() +"_"+dto.getArticleId()).set("");
            }else{
                redisTemplate.delete( methodName +dto.getUserId()+"_"+dto.getEquipmentId()+"_"+dto.getAuthorId() +"_"+dto.getArticleId());
            }
        }

        try {
            return pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }



}
